<script setup lang="ts">
import { HomeWrap } from '@/components/HomeWrap'
import { login } from '@/api/user/client'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie'
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

defineOptions({
  name: 'UserLogin'
})

const formRef = ref<FormInstance>()
const router = useRouter()
const route = useRoute() // 获取当前路由信息

const form = reactive({
  phone: '',
  password: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
    // { pattern: /^1\d{10}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  password: [
    // 修改验证规则字段名
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度 6-20 位', trigger: 'blur' }
  ]
}

const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 调用登录 API
        const res = await login({
          phone: form.phone,
          password: form.password
        })

        if (res) {
          // 将 token 存储到 cookie 中
          Cookies.set('user_token', res.data.token, { expires: 365 }) // 设置7天过期

          ElMessage.success('登录成功')

          // 获取来源页面，如果没有则跳转到首页
          const redirect = (route.query.redirect as string) || '/home'

          // 登录成功后跳转到来源页面
          router.push(redirect)
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败')
      }
    }
  })
}

const goToRegister = () => {
  router.push('/user-register')
}
</script>
<template>
  <HomeWrap>
    <div class="login-card">
      <h2>登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            maxlength="11"
            type="tel"
            size="large"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
            size="large"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="large" style="width: 100%" @click="submit">
            提交
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="success" size="large" style="width: 100%" @click="goToRegister">
            无账号？去注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </HomeWrap>
</template>

<style scoped>
.login-card {
  margin-top: 80px;
  padding: 24px;
}

h2 {
  text-align: center;
  margin-bottom: 24px;
}

:deep(.el-input) {
  height: 50px;
}

:deep(.el-input__inner) {
  height: 50px;
  font-size: 16px;
}
</style>
